import FSTool from '../lib/FSTool';
import path from 'path';
import stringMd5 from '../lib/FSTool/stringMd5';
import configTool from '../com/configTool';
// @ts-ignore
import colors from 'colors-console';
import CryptoUtil from '../lib/CryptoUtil';

class Authentication {

    static serverId = '';

    // 保存机器码以备用
    static async getServerId() {
        await configTool.init();

        if (Authentication.serverId) {
            return Authentication.serverId;
        }

        // 获取硬件【特征码】
        const SerialNumber = configTool.serverInfo.machineId;
        // 服务器唯一【机器码】
        this.serverId = stringMd5(SerialNumber);

        return this.serverId;
    }


    static async Verification() {
        await configTool.init();

        const serverId = await Authentication.getServerId();

        // 请使用一个随机的字符串，用作 AES 的解密秘钥
        const AESPassword = 'cbAK8wDRwiXkBxnDHUquiRjHyceR3b';
        // 内部授权码
        const insideAuthorizationCode = stringMd5(serverId);


        return new Promise(async (resolve) => {
            try {
                const enLicenseObjTxt = FSTool.readFileSync(path.join(configTool.appBasePath, '/temp/serverId.lic')).toString();

                try {
                    const licenseObjTxt = CryptoUtil.Decrypt(enLicenseObjTxt, AESPassword);
                    const licenseObj = JSON.parse(licenseObjTxt);

                    // 2024-12-30
                    const currentDate = new Date().toISOString().split('T')[0];
                    const beginDate = new Date(licenseObj.beginDate).toISOString().split('T')[0];
                    const endDate = new Date(licenseObj.endDate).toISOString().split('T')[0];

                    if (currentDate < beginDate || currentDate > endDate) {
                        console.log(colors('red', `【授权码，错误！！】当前日期不在授权范围内，当前日期：` + new Date().toISOString()));
                        resolve(false);
                    } else if (licenseObj.outAuthorizationCode !== insideAuthorizationCode) {
                        console.log(colors('red', `【授权码，验证失败】设备标识码不匹配，当前日期：` + new Date().toISOString()));
                        resolve(false);
                    } else {
                        // 授权日期还剩
                        // @ts-ignore
                        const lastDay = Math.floor((new Date(endDate) - new Date(currentDate)) / (1000 * 60 * 60 * 24));
                        console.log(colors('green', `【外部授权码，校验成功】：还剩 ${lastDay} 天使用期，授权文件位置：${
                            path.join(configTool.appBasePath, '/temp/serverId.lic')
                        }`));

                        resolve(licenseObj);
                    }
                } catch (e) {
                    console.log(colors('red', `【授权码，错误！！】当前日期：` + new Date().toISOString()));
                    resolve(false);
                }


            } catch (e) {
                console.log(colors('red', `权限错误：在路径【${path.join(configTool.appBasePath, '/temp/serverId.lic')}】下，找不到授权文件 serverId.lic，系统启动失败！！`));
                resolve(false);
            }
        });
    }
}

export default Authentication;